using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Configuration;
using System.Collections;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using Microsoft.ApplicationBlocks.Data;
using Microsoft.AceEngineering.SPM.SPMBusinessLayer;
using Microsoft.AceEngineering.SPM.SPMCustomDataEntity;

public partial class Risk_Default : Page
{
    protected void MaxThreshold()
    {
        ThresholdCDE thresholdData = WTRIAssessmentBL.GetQuestionMaxAnswerWt();

        if (thresholdData != null)
        {
            if (thresholdData.MaxTotal > thresholdData.MaxThreshold)
            {
                btnSubmit.Visible = false;
                btnSave.Visible = false;
                if (lblStatus.Text.Equals("In Progress"))
                {
                    lblError.Text = "The score ranges and answer weights do not match. Please notify your system administrator.";
                    lblStatus.Text = "Error";
                    pnlError.Visible = true;
                }
            }
        }
    }

    protected void BindCatRepeaters1(int appID)
    {
        rtpCategory1.DataSource = WTRIAssessmentBL.dsLoadAssessmentDataSet("SPM_spGetAssesmentCategories", appID).Tables[0];
        rtpCategory1.DataBind();
    }

    protected void BindCatRepeaters(int action)
    {
        string strproc = "SPM_spgetCategory";
        if (action == 2)
            strproc = "APM_spgetStagingCategory";

        rptCategory.DataSource = WTRIAssessmentBL.dsLoadDataSet(strproc).Tables[0];
        rptCategory.DataBind();
    }

    private string GiveMeAlias(string domainAndAlias)
    {
        domainAndAlias = domainAndAlias.ToLower();
        char[] strSeperator = new char[] { '\\' };
        string[] aryAuthUser = new string[2];
        aryAuthUser = domainAndAlias.Split(strSeperator);
        return aryAuthUser[1];
    }

    private void ValidateUser()
    {
        string currAlias = GiveMeAlias(HttpContext.Current.User.Identity.Name);
        UserCDE user = UsersBL.ValidateUser(currAlias);
        if (user.Active)
        {
            Session["user"] = user;
            Session["loginname"] = user.UserAlias;
        }
        else
        {
            Response.Redirect(Request.ApplicationPath + "/Errors/NoAccess.htm");
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["user"] == null)
            ValidateUser();
        else
        {
            UserCDE userData = (UserCDE)Session["user"];
            if (userData.Time.AddMinutes(Int32.Parse(ConfigurationManager.AppSettings["AbsoluteExpiration"].ToString())) <= DateTime.Now)
                ValidateUser();
        }

        int intAction = 0;
        int intAppID = 0;
        bool boolAppID = Int32.TryParse(Request.QueryString["ID"], out intAppID);
        bool boolAction = Int32.TryParse(Request.QueryString["Action"], out intAction);           

        if (!Page.IsPostBack)
        {
            if (boolAction)
            {
                if (intAction == 1)
                    lblStatus.Text = "Preview Published Task Risk Impact Assessment";
                else if (intAction == 2)
                    lblStatus.Text = "Preview Staging Task Risk Impact Assessment";
                else
                    Response.Redirect("~/Workflow/Default.aspx");

                lblAppID.Text = "Sample Application ID";
                lblAppName.Text = "Sample Application Name";
                lblVersion.Text = "Sample Application Version";
                pnlSearch.Visible = false;
                pnlAppAssessment.Visible = true;
                pnlAssessmentNotCompleted.Visible = true;
                btnSave.Visible = false;
                btnCancel.ToolTip = "Back to Risk Impact Assessment";
                btnSubmit.Visible = false;
                BindCatRepeaters(intAction);
            }
            else if (boolAppID)
            {
                try
                {
                    hfAppID.Value = intAppID.ToString();
                    int score = WTRIAssessmentBL.GetValidateScoreExist(intAppID);
                    pnlSearch.Visible = false;
                    pnlAppAssessment.Visible = true;
                    btnCancel.ToolTip = "Back to View Application Data";

                    if (score == -1)
                    {
                        btnSave.Visible = true;
                        btnSubmit.Visible = true;
                        lblStatus.Text = "In Progress";
                        ValidateUserContact(intAppID, Session["loginname"].ToString());
                        pnlAssessmentNotCompleted.Visible = true;
                        pnlAssessmentCompleted.Visible = false;

                        BindCatRepeaters(0);
                    }
                    else
                    {
                        btnSave.Visible = false;
                        btnSubmit.Visible = false;
                        lblStatus.Text = "<font color='green'>Completed</font>";
                        pnlAssessmentCompleted.Visible = true;
                        pnlAssessmentNotCompleted.Visible = false;
                        BindCatRepeaters1(intAppID);
                    }
                    BindAppInfo(intAppID);
                }
                catch
                {
                    Response.Redirect("~/Workflow/Default.aspx");
                }
            }
            else
            {
                btnCancel.ToolTip = "Back to Task Risk Impact Assessment - Application Quick Search";
            }
        }
    }

    protected void CancelClick(object source, EventArgs e)
    {
        if (Request.QueryString["id"] != null)
        {
            int intAppID = Int32.Parse(Request.QueryString["ID"]);
            Response.Redirect("~/Application/ApplicationDataEntryView.aspx?id=" + intAppID);
        }
        else if (Request.QueryString["action"] != null)
        {
            Response.Redirect("~/Admin/Risk/Categories.aspx");
        }
        else
        {
            Session["search"] = null;
            pnlAppAssessment.Visible = false;
            pnlSearch.Visible = true;
        }
    }

    protected void SubmitClick(object source, EventArgs e)
    {
        UploadResponses(true);
    }

    protected void SaveClick(object source, EventArgs e)
    {
        UploadResponses(false);
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            //Try to parse the search parameter if it can be converted to Integer value
            int searchByID;
            int intSearchType = Int32.Parse(rdsearchType.SelectedValue.ToString());

            bool IDFound = Int32.TryParse(txtSearch.Text, out searchByID);
            if (intSearchType == 1)
            {
                try
                {
                    if (IDFound)// Search parameter is an Integer value so search will be either on application name or application id
                        Search(string.Empty, searchByID);
                    else
                        throw new Exception("APMError021");
                }
                catch (Exception ex)
                {
                    string strErrorType = ex.Message.ToString().Substring(0, 8);

                    Page pge = (Page)this.Page;
                    Microsoft.ACEEngineering.Utility.CommonProcess.APMErrorHandling(ex, Request.IsLocal, pge, Session, Request);
                    if (!Request.IsLocal && strErrorType != "APMError")
                    {
                        Server.ClearError();
                        Server.Transfer(Request.ApplicationPath + "/Errors/GenericErrorPage.htm");
                    }
                }
            }
            else
            {
                //Search parameter is a string so search will be on application name
                Search(txtSearch.Text, 0);
            }
        }
        else
        {
            string msg = "Please correct the following:\\n- Required Field: Application Name/ID";
            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, msg, "errorkey");
        }
    }

    protected void Search(string name, int id)
    {
        try
        {
            ArrayList list = ApplicationsBL.GetSearchApplicationData(name, id);

            lstApplicationNames.Items.Clear();
            foreach (ListItem lstTemp in list)
            {
                lstApplicationNames.Items.Add(lstTemp);
            }
            lstApplicationNames.Visible = true;
            lblResult.Visible = true;
            btnGo.Visible = true;
        }
        catch (Exception ex)
        {
            string strErrorType = ex.Message.ToString().Substring(0, 8);

            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.APMErrorHandling(ex, Request.IsLocal, pge, Session, Request);
            if (!Request.IsLocal && strErrorType != "APMError")
            {
                Server.ClearError();
                Server.Transfer(Request.ApplicationPath + "/Errors/GenericErrorPage.htm");
            }
            btnGo.Visible = false;
            lstApplicationNames.Visible = false;
            lblResult.Visible = false;
        }
    }

    protected void BindAppInfo(int intAppID)
    {
        ApplicationCDE appData = WTRIAssessmentBL.GetApplicationInfoByAppID(intAppID);

        lblAppID.Text = Microsoft.Security.Application.AntiXss.HtmlEncode(appData.ApplicationID.ToString());
        lblAppName.Text = Microsoft.Security.Application.AntiXss.HtmlEncode(appData.ApplicationName);
        lblVersion.Text = Microsoft.Security.Application.AntiXss.HtmlEncode(appData.ApplicationVersion);

        //Possible answers that were saved before
        string strAnswersSelected = appData.AssessmentData;

        if (strAnswersSelected != string.Empty)
        {
            XmlDocument xmlSelectedAns = new XmlDocument();
            xmlSelectedAns.LoadXml(strAnswersSelected);

            foreach (RepeaterItem ri in rptCategory.Items)
            {
                Repeater rptQuest = (Repeater)ri.FindControl("rptQuestions");
                foreach (RepeaterItem rptQuestTxt in rptQuest.Items)
                {
                    DropDownList ddlSelectedAns = (DropDownList)rptQuestTxt.FindControl("ddlAnswers");
                    XmlNode xmlAnswerID;
                    foreach (ListItem liAns in ddlSelectedAns.Items)
                    {
                        if (liAns.Value != string.Empty)
                        {
                            Guid liAnsGUID = new Guid(liAns.Value.ToString());

                            XmlNode rtAnswer = xmlSelectedAns.DocumentElement;
                            xmlAnswerID = rtAnswer.SelectSingleNode("//AppRisk/Responses/AnswerID[.  ='" + liAnsGUID + "']");
                            if (xmlAnswerID != null)
                            {
                                ddlSelectedAns.SelectedValue = liAnsGUID.ToString();
                                break;
                            }
                        }
                    }
                }
            }
        }
        //This Will Block the Save and Submit buttons if the Weights doens't match the Scores
        MaxThreshold();
    }

    protected void rptCategory1_ItemDataBound(object source, RepeaterItemEventArgs e)
    {
        int intAppID = Int32.Parse(hfAppID.Value);
        DataView dvQuestions = WTRIAssessmentBL.dsLoadAssessmentDataSet("SPM_spGetAssesmentQuestions", intAppID).Tables[0].DefaultView;
        DataView dvAnswers = WTRIAssessmentBL.dsLoadAssessmentDataSet("SPM_spGetAssesmentQuestions", intAppID).Tables[0].DefaultView;

        foreach (RepeaterItem ri in rtpCategory1.Items)
        {
            Label catName = (Label)ri.FindControl("lblCatName");
            dvQuestions.RowFilter = "Category='" + catName.Text.ToUpper() + "'";

            Repeater rptQuest = (Repeater)ri.FindControl("rptQuestions1");
            rptQuest.DataSource = dvQuestions;
            rptQuest.DataBind();
            int i = 1;

            foreach (RepeaterItem riQ in rptQuest.Items)
            {
                Label lblQuestionOrder = (Label)riQ.FindControl("lblSeqOrder1");
                lblQuestionOrder.Text = i.ToString();

                Label questName = (Label)riQ.FindControl("lblQuestText1");
                dvAnswers.RowFilter = "Question='" + questName.Text.ToUpper() + "'";

                Label answer = (Label)riQ.FindControl("lblAnswer1");
                string k = dvAnswers.ToString();
                i = i + 1;
            }
        }
    }

    protected void rptCategory_ItemDataBound(object source, RepeaterItemEventArgs e)
    {
        int intAction = 0;
        bool blAction = Int32.TryParse(Request.QueryString["Action"], out intAction);

        string strQuestStoredProc = "SPM_spgetQuestions";
        string strAnsStoredProc = "SPM_spgetAnswers";

        if (intAction == 2)
        {
            strQuestStoredProc = "APM_spgetStagingQuestions";
            strAnsStoredProc = "APM_spgetStagingAnswers";
        }

        DataView dvQuestions = WTRIAssessmentBL.dsLoadDataSet(strQuestStoredProc).Tables[0].DefaultView;
        DataView dvAnswers = WTRIAssessmentBL.dsLoadDataSet(strAnsStoredProc).Tables[0].DefaultView;

        foreach (RepeaterItem ri in rptCategory.Items)
        {
            TextBox txtCID = (TextBox)ri.FindControl("txtCatID");
            dvQuestions.RowFilter = "QuestionCategoryID='" + txtCID.Text.ToUpper() + "'";

            Repeater rptQuest = (Repeater)ri.FindControl("rptQuestions");
            rptQuest.DataSource = dvQuestions;
            rptQuest.DataBind();
            int i = 1;

            foreach (RepeaterItem riQ in rptQuest.Items)
            {
                Label lblQuestionOrder = (Label)riQ.FindControl("lblSeqOrder");
                lblQuestionOrder.Text = i.ToString();

                TextBox txtQID = (TextBox)riQ.FindControl("txtQuestID");
                dvAnswers.RowFilter = "QuestionID='" + txtQID.Text.ToUpper() + "'";

                DropDownList ddlAns = (DropDownList)riQ.FindControl("ddlAnswers");
                ddlAns.DataSource = dvAnswers;
                ddlAns.DataBind();
                i = i + 1;
            }
        }
    }

    private void UploadResponses(bool isLocked)
    {
        try
        {
            int intAppID = Int32.Parse(hfAppID.Value);
            DataSet dsXML = new DataSet("AppRisk");

            DataTable dt = new DataTable("AppInfo");
            DataColumn[] column = new DataColumn[3];
            column[0] = new DataColumn("AppID", System.Type.GetType("System.Int32"));
            dt.Columns.Add(column[0]);
            column[1] = new DataColumn("CreatedBy", System.Type.GetType("System.String"));
            dt.Columns.Add(column[1]);
            column[2] = new DataColumn("CreatedDate", System.Type.GetType("System.DateTime"));
            dt.Columns.Add(column[2]);

            DataRow dr = dt.NewRow();
            dr["AppID"] = intAppID;
            dr["CreatedBy"] = Session["loginname"].ToString();
            dr["CreatedDate"] = System.DateTime.Now;
            dt.Rows.Add(dr);

            dsXML.Tables.Add(dt);

            DataTable dtResp = new DataTable("Responses");
            DataColumn[] colResp = new DataColumn[6];
            colResp[0] = new DataColumn("Category", System.Type.GetType("System.String"));
            dtResp.Columns.Add(colResp[0]);
            colResp[1] = new DataColumn("SortOrder", System.Type.GetType("System.Int32"));
            dtResp.Columns.Add(colResp[1]);
            colResp[2] = new DataColumn("Question", System.Type.GetType("System.String"));
            dtResp.Columns.Add(colResp[2]);
            colResp[3] = new DataColumn("Answer", System.Type.GetType("System.String"));
            dtResp.Columns.Add(colResp[3]);
            colResp[4] = new DataColumn("RCount", System.Type.GetType("System.Int32"));
            dtResp.Columns.Add(colResp[4]);
            colResp[5] = new DataColumn("AnswerID", System.Type.GetType("System.String"));
            dtResp.Columns.Add(colResp[5]);
            dsXML.Tables.Add(dtResp);

            string strSelectAnsID = null;
            int i = 0;
            foreach (RepeaterItem ri in rptCategory.Items)
            {
                TextBox txtCategory = (TextBox)ri.FindControl("txtCatName");
                string strCategory = txtCategory.Text;
                clsResponse clsR = new clsResponse();
                clsR.Category = txtCategory.Text;

                Repeater rptQuest = (Repeater)ri.FindControl("rptQuestions");

                clsR.ResponseCount = rptQuest.Items.Count;
                i = rptQuest.Items.Count + 1;

                DataRow[] drResp = new DataRow[i];
                foreach (RepeaterItem rptQuestTxt in rptQuest.Items)
                {
                    TextBox txtQuestTxt = (TextBox)rptQuestTxt.FindControl("txtQuestionTxt");
                    string strQuestTxt = txtQuestTxt.Text;
                    clsR.Question = strQuestTxt;

                    Label lblQuestOrder = (Label)rptQuestTxt.FindControl("lblSeqOrder");
                    int intQuestOrder = Int32.Parse(lblQuestOrder.Text);

                    DropDownList ddlSelectedAns = (DropDownList)rptQuestTxt.FindControl("ddlAnswers");
                    string strSelectedAns = ddlSelectedAns.SelectedItem.Text.ToString();
                    clsR.Answer = strSelectedAns;

                    strSelectAnsID = ddlSelectedAns.SelectedValue.ToString();

                    drResp[intQuestOrder] = dtResp.NewRow();
                    drResp[intQuestOrder]["Category"] = clsR.Category;
                    drResp[intQuestOrder]["SortOrder"] = intQuestOrder;
                    drResp[intQuestOrder]["Question"] = strQuestTxt;
                    drResp[intQuestOrder]["Answer"] = strSelectedAns;
                    drResp[intQuestOrder]["AnswerID"] = strSelectAnsID;
                    drResp[intQuestOrder]["RCount"] = clsR.ResponseCount;
                    dtResp.Rows.Add(drResp[intQuestOrder]);
                }
            }

            Guid strID = System.Guid.NewGuid();

            System.IO.MemoryStream xmlStream = new System.IO.MemoryStream();
            dsXML.WriteXml(xmlStream, XmlWriteMode.IgnoreSchema);
            xmlStream.Position = 0;

            WTRIAssessmentBL.AddResponses(strID, xmlStream, intAppID, isLocked, Session["loginname"].ToString());

            Page pge = (Page)this.Page;
            if (isLocked)
                Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, "The answers were successfully submitted to the system.", "errorkey");
            else
                Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, "The answers were successfully saved into the system.", "errorkey");

            if(isLocked)
            {
                btnSave.Visible = false;
                btnSubmit.Visible = false;
                lblStatus.Text = "<font color='green'>Completed</font>";
                pnlAssessmentCompleted.Visible = true;
                pnlAssessmentNotCompleted.Visible = false;
                rptCategory.DataSource = null;
                BindCatRepeaters1(intAppID);
            }
        }
        catch (Exception ex)
        {
            string strErrorType = ex.Message.ToString().Substring(0, 8);

            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.APMErrorHandling(ex, Request.IsLocal, pge, Session, Request);
            if (!Request.IsLocal && strErrorType != "APMError")
            {
                Server.ClearError();
                Server.Transfer("~/Errors/GenericErrorPage.htm");
            }
        }
    }

    private void ValidateUserContact(int intAppid, string strUserAlias)
    {
        if (ConfigurationManager.AppSettings["RestictUpdatesToContacts"].ToString().ToUpper() == "TRUE")
        {
            int intAppID = Int32.Parse(hfAppID.Value);
            int qty = WTRIAssessmentBL.RestictUpdatesToContacts(intAppID, Session["loginname"].ToString());
            if (qty == 0)
            {
                btnSave.Visible = false;
                btnSubmit.Visible = false;
                pnlError.Visible = true;
                lblStatus.Text = "Error";
                lblError.Text = "Insufficient Permissions to Update";
            }
        }
    }

    public class clsResponse
    {
        public string Category;
        public int ResponseCount;
        public string Question;
        public string Answer;
    }

    protected void btnGo_Click(object sender, EventArgs e)
    {
        if (lstApplicationNames.SelectedIndex != -1)
        {
            int intAppID = Int32.Parse(lstApplicationNames.SelectedValue);
            hfAppID.Value = intAppID.ToString();

            int score = WTRIAssessmentBL.GetValidateScoreExist(intAppID);

            pnlSearch.Visible = false;
            pnlError.Visible = false;
            pnlAppAssessment.Visible = true;

            if (score == -1)
            {
                btnSave.Visible = true;
                btnSubmit.Visible = true;
                lblStatus.Text = "In Progress";
                ValidateUserContact(intAppID, Session["loginname"].ToString());
                pnlAssessmentNotCompleted.Visible = true;
                pnlAssessmentCompleted.Visible = false;

                BindCatRepeaters(0);
            }
            else
            {
                btnSave.Visible = false;
                btnSubmit.Visible = false;
                lblStatus.Text = "<font color='green'>Completed</font>";
                pnlAssessmentCompleted.Visible = true;
                pnlAssessmentNotCompleted.Visible = false;
                BindCatRepeaters1(intAppID);
            }
            BindAppInfo(intAppID);
        }
        else
        {
            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, "No application was selected.", "errorkey");
        }
    }
}

